package com.xiaoyao.novel.filter;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.xiaoyao.novel.service.ChapterService;
import com.xiaoyao.novel.service.ClickService;
import com.xiaoyao.novel.util.FileUtil;
import com.xiaoyao.novel.util.HtmlStatic;

/**
 * 静态页面过滤器
 * 
 * @author 旷明爱
 * @date Dec 13, 2012 9:13:38 AM
 */
public class StaticFilter implements Filter {
	private static Logger logger = Logger.getLogger(StaticFilter.class);
	static String regex = "((chapter)|(book)|(list))/(\\d+).html";
	static Pattern pattern = Pattern.compile(regex);
	static ChapterService chapterService = new ChapterService();
	static int LEAST_PAGE_SIZE = 4 * 1024;// 页面最小字节数
	static int MAX_IP_BOOK_PAGE = 30;// 风险IP访问书籍页面 阈值
	static int IP_MAX_CACHE = 1000;// Cache 最大值
	static int LAST_DATE = 0;// 上次记录的日期号
	static Map<String,Integer> ipVisitMap =new HashMap<String, Integer>() ; //IP 访问记录
	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		// 获取IP
		String ip = "";
		if (httpRequest.getHeader("x-forwarded-for") == null) {
			ip = httpRequest.getRemoteAddr();
		} else {
			ip = httpRequest.getHeader("x-forwarded-for");
		}
		//httpResponse.setCharacterEncoding("UTF-8");// 在 JSPFilter 里面统一设置编码
		String uri = httpRequest.getRequestURI().replaceFirst("/novel", "");
		if (uri.endsWith("html")) { // html页面
			// 找出页面类型.ID
			Matcher matcher = pattern.matcher(uri);
			String html = "";
			String type = "";
			Integer id = 0;
			if (matcher.find()) {
				type = matcher.group(1);
				id = Integer.parseInt(matcher.group(5));
			}
			// 页面是否存在
			File file = new File(FileUtil.getWebRoot() + uri);
			boolean exist = file.exists();
			if (type.equals("book")) {// 记录点击// 记录IP//用程序分析日志IP.
				logger.warn( "访问IP:" + ip + ";页面:" + uri);// /novel/chapter/50.html
				ClickService.click(id);
				//////////IP 记录// Cache 来做.
//				//隔天,清空
//				Integer ipCount =ipVisitMap.get(ip) ;
//				if (ipCount==null) {
//					ipCount=1;
//				}else if (ipCount>MAX_IP_BOOK_PAGE) { // 访问书籍页30次
//					logger.warn("风险IP(书籍页>"+MAX_IP_BOOK_PAGE+"次):"+ip+";"+ipCount);
//				}  
//				ipCount++;
//				ipVisitMap.put(ip, ipCount);
//				if (ipVisitMap.size()>IP_MAX_CACHE) {
//					
//				}
			}
			if (!exist || file.length() < LEAST_PAGE_SIZE) { // 不存在或者小于5K,生成
				if (type.equals("chapter")) {// 暂时不记录章节的点击.耗费资源
					html = HtmlStatic.staticChapter(id, true);
				} else if (type.equals("book")) {
					html = HtmlStatic.staticBook(id);
				} else if (type.equals("list")) {
					html = HtmlStatic.staticCategory(id);
				}
				if (html.startsWith("error")) {
					request.getRequestDispatcher("../").forward(httpRequest, httpResponse);
				} else {
					httpResponse.getWriter().write(html);
				}
				return;
			}
		}
		chain.doFilter(request, response);
	}

	public void destroy() {
	}

	public void init(FilterConfig arg0) throws ServletException {
	}
}